(function ($, _, amplify, window, document) {
    'use strict';

    var rootElem,
        formElem,
        linkTableBody,
        includeIcons,
        buildButton;

    $(document).ready(function () {
        rootElem        = $('#natext .smm-builder');
        formElem        = $('.main-form', rootElem);
        linkTableBody   = $('.smm-builder-tbody', formElem);
        includeIcons    = $('[name="include_icons"]', formElem);
        buildButton     = $('.build-button', formElem);


        // Event Listeners
        // ------------------------------
        formElem.submit(formElem_onSubmit);
    });


    // Event Handlers
    // ------------------------------

    function formElem_onSubmit(evt) {
        // prevent the form from submitting to its action URL
        // we'll do it the AJAX way
        evt.preventDefault();

        var links       = getValidLinks(),
            linksLen    = _.size(links),
            linkCount   = 0;

        var createLink  = function () {
            var link = links[linkCount];

            // tell the user that we are currently creating the link
            amplify.publish('creatingLink', {sideNote: link.sideNote});

            $.ajax({
                type    : 'POST',
                url     : NatExt.wp.ajax_url,
                data    : {
                    'action'        : 'NatExtAjax_BuildSMM',
                    'link_name'     : link.link_name,
                    'link_url'      : link.link_url,
                    'link_image'    : link.row.attr('data-icon'),
                    'include_icons' : includeIcons.is(':checked')
                },
                success : function () {
                    amplify.publish('linkCreated', {
                        row : link.row,
                        sideNote : link.sideNote
                    });
                },
                complete : function () {
                    linkCount += 1;

                    if (linkCount < linksLen) {
                        createLink();
                    }
                }
            });
        };

        if (links.length) {
            // we have valid links, let's create those

            // hide the build button first
            buildButton.fadeOut(200);

            createLink();
        }
    }


    // Subscriptions
    // ------------------------------

    amplify.subscribe('creatingLink', __creatingLink);
    amplify.subscribe('linkCreated', __linkCreated);

    function __creatingLink(data) {
        if (! data.sideNote.hasClass('creating-link')) {
            data.sideNote.html('creating link...').addClass('creating-link');
        }
    }

    function __linkCreated(data) {
        if (! data.sideNote.hasClass('link-created')) {
            data.sideNote.html('link created').addClass('link-created');
        }

        // disable the fields on this row
        $('input', data.row).attr('disabled', 'disabled');

        // uncheck this row
        $('input[type=checkbox]', data.row).removeAttr('checked');
    }


    // Utils
    // ------------------------------

    function getValidLinks() {
        var checkedRows,
            result = [];

        // get all rows of checked pages
        checkedRows = $('input[type=checkbox]:checked', linkTableBody).closest('tr');

        checkedRows.each(function () {
            var row = $(this).get()[0];

            if (hasValidLinkData(row)) {
                result.push(getLinkData(row));
            }
        });

        return result;
    }

    function getLinkData(row) {
        return {
            'row'           : $(row),
            'link_name'     : $('input', $(row.cells[1])).val(),
            'link_url'      : $('input', $(row.cells[2])).val(),
            'sideNote'      : $(row.cells[3])
        };
    }

    function hasValidLinkData(row) {
        var linkData = getLinkData(row);

        return (($.trim(linkData.link_name) !== '') && ($.trim(linkData.link_url) !== ''));
    }
}(jQuery, _, amplify, window, document));